package com.cyanite.playlv2;

import com.cyanite.playlv2.blog.DoubanBlogManager;
import com.cyanite.playlv2.blog.SinaBlogManager;
import com.cyanite.playlv2.preferences.Preferences;
import com.cyanite.playlv2.util.NotificationsUtil;
import com.cyanite.playlv2api.PlayLv2Api;
import com.cyanite.playlv2api.types.Response;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Blog bind activity, if account has been saved into preference, 
 * it will directly sync your checkin to blogs
 * 
 */
public class BlogBindActivity extends Activity  {

    private static class BlogBindTask extends AsyncTask<Void, Void, Response> {

        private BlogBindActivity mActivity;
        private Exception mReason;
        private String mAccount;
        private String mPassword;

        public BlogBindTask(BlogBindActivity activity, String account, String password) {
            mActivity = activity;
            mAccount = account;
            mPassword = password;
        }

        @Override
        protected Response doInBackground(Void... params) {
            PlayLv2Api playlv2api = ((PlayLv2) mActivity.getApplication()).getPlayLv2Api();
            try {
                Response response = playlv2api.bindBlog(mAccount, mPassword);
                if (response == null)   response = new Response();
                return response;
            } catch (Exception ex) {
                mReason = ex;
                return null;
            }
        }

        @Override
        protected void onCancelled() {
            mActivity.dismissProgressDialog();
        }

        @Override
        protected void onPostExecute(Response response) {
            if (mActivity != null) {
                mActivity.onBlogBindTaskComplete(response, mReason);
            }
        }

        @Override
        protected void onPreExecute() {
            mActivity.showProgressDialog();
        }

        public void setActivity(BlogBindActivity activity) {
            mActivity = activity;
        }
    }

    private static class StateHolder {

        private BlogBindTask mTaskBlogBind;
        private boolean mIsRunningBlogBindTask;
        private int mItemChoosed;
        private boolean mItemBindStatus;
        private boolean mIsMainPage;

        public StateHolder() {
            mIsRunningBlogBindTask = false;
            mItemBindStatus = false;
            mItemChoosed = -1;
            mIsMainPage = false;
        }

        public void cancelTasks() {
            if (mTaskBlogBind != null) {
                mTaskBlogBind.setActivity(null);
                mTaskBlogBind.cancel(true);
            }
        }

        public boolean getIsMainPage()  {
            return mIsMainPage;
        }

        public boolean getItemBindStatus()  {
            return mItemBindStatus;
        }

        public int getItemChoosed() {
            return mItemChoosed;
        }

        public void setIsMainPage(boolean isMainPage)   {
            mIsMainPage = isMainPage;
        }

        public void setIsRunningBlogBindTask(boolean isRunning) {
            mIsRunningBlogBindTask = isRunning;
        }

        public void setItemBindStatus(boolean bindstatus)    {
            mItemBindStatus = bindstatus;
        }

        public void setItemChoosed(int item)    {
            mItemChoosed = item;
        }

        public void startTaskBlogBind(BlogBindActivity activity, String account, String password) {
            if (!mIsRunningBlogBindTask) {
                mIsRunningBlogBindTask = true;
                mTaskBlogBind = new BlogBindTask(activity, account, password);
                mTaskBlogBind.execute();
            }
        }
    }
    
    public static final String EXTRA_MAIN = PlayLv2.PACKAGE_NAME
        + ".BlogBindActivity.EXTRA_MAIN";
    private static int BLOGITEMCOUNT = 4;

    private int mBlogIcon[] = { R.drawable.kaixin001, R.drawable.renren,R.drawable.gtalk, R.drawable.sina};
    private int mBlogName[] = { R.string.blog_kaixin, R.string.blog_renren,R.string.blog_gtalk, R.string.blog_sina};
    private StateHolder mStateHolder;
    private ProgressDialog mProgressDialog;
    private ArrayList<HashMap<String, Object>> mListItem;
    private EditText mUserName;
    
    private EditText mPassword;

    private AlertDialog mAlertDlg;

    private SinaBlogManager mSinaBlogManager;
    private DoubanBlogManager mDoubanBlogManager;

    private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    };


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerReceiver(mLoggedOutReceiver, new IntentFilter(PlayLv2.INTENT_ACTION_LOGGED_OUT));
        setContentView(R.layout.blog_bind_activity);

        mStateHolder = new StateHolder();
        if (getIntent().hasExtra(EXTRA_MAIN)) {
            mStateHolder.setIsMainPage(
                    getIntent().getExtras().getInt(EXTRA_MAIN) == 1? true : false);
        }
        ensureUi();
        
        if (mSinaBlogManager != null) {
            handleSinaAuthCallBack();
        }
        if (mDoubanBlogManager != null) {
            handleDoubanAuthCallBack();
        }
    }

    private void dismissProgressDialog() {
        try {
            mProgressDialog.dismiss();
        } catch (IllegalArgumentException e) {
            // We don't mind. android cleared it for us.
        }
    }

    private void ensureUi() {

        setTitle(getString(R.string.blog_bind_activity_label));

        initBlogBindList();

        ListView mListView = (ListView)findViewById(R.id.lvBlogList);
        SimpleAdapter listAdapter = new SimpleAdapter( this,
                                                    mListItem,
                                                    R.layout.blog_list_item,
                                                    new String[] {"ItemImage","ItemTitle", "ItemText"},
                                                    new int[] {R.id.itemImage, R.id.itemTitle, R.id.itemText });

        mListView.setAdapter(listAdapter);
        mListView.setOnItemClickListener(new OnItemClickListener()  {
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
                mStateHolder.setItemChoosed(arg2);
                mStateHolder.setItemBindStatus(Preferences.getBindStatusByIndex(((PlayLv2) getApplication()).getPrefs(), arg2));
                if (mStateHolder.getItemBindStatus()) {
                    popUpBlogUnbindDialog();
                } else {
                    switch (arg2) {
                        case 2:
                            mDoubanBlogManager = new DoubanBlogManager(BlogBindActivity.this);
                            mDoubanBlogManager.bind();
                            break;
                        case 3:
                            mSinaBlogManager = new SinaBlogManager(BlogBindActivity.this);
                            mSinaBlogManager.bind();
                            break;
                        default:
                            break;
                    }
                    // popUpBlogBindDialog( mBlogIcon[arg2], mBlogName[arg2] );
                }
            }
        });

        Button mBtnBlogDone = (Button)findViewById(R.id.btnBlogDone);
        mBtnBlogDone.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mStateHolder.getIsMainPage()){
                    Intent intent = new Intent(BlogBindActivity.this, MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                }
                finish();
            }
        });
    }

    private Boolean handleDoubanAuthCallBack() {
        return mDoubanBlogManager.handleAuthCallBack();
    }

    private Boolean handleSinaAuthCallBack() {
        Uri uri = getIntent().getData();
        if (uri != null)
            return mSinaBlogManager.handleAuthCallBack(uri);
        else
            return false;
    }

    private void initBlogBindList() {
        mListItem = new ArrayList<HashMap<String, Object>>();
        PlayLv2 playlv2 = (PlayLv2) getApplication();
        for ( int index = 0; index < BLOGITEMCOUNT; index++ )   {
            HashMap<String, Object> mHashMap = new HashMap<String, Object>();
            mHashMap.put("ItemImage", mBlogIcon[index]);
            mHashMap.put("ItemTitle", this.getString(mBlogName[index]));
            mHashMap.put("ItemText", Preferences.getBindStatusByIndex(playlv2.getPrefs(), index) == true? getString(R.string.blog_bind):getString(R.string.blog_unbind));
            mListItem.add(mHashMap);
        }
    }

    private void onBlogBindTaskComplete(Response response, Exception ex) {
        mStateHolder.setIsRunningBlogBindTask(false);
        dismissProgressDialog();

        if (response != null && response.getValue().equals("0")) {
            PlayLv2 playlv2 = (PlayLv2) getApplication();
            Preferences.setBindStatusByIndex(playlv2.getPrefs(), mStateHolder.getItemChoosed(), !mStateHolder.getItemBindStatus());

        } else {
            NotificationsUtil.ToastReasonForFailure(this, ex);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mLoggedOutReceiver);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)   {
        if (keyCode == KeyEvent.KEYCODE_BACK && mStateHolder.getIsMainPage()){
            Intent intent = new Intent(BlogBindActivity.this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();
            return true;
        } 
        // TODO 4 del
        else if (keyCode==KeyEvent.KEYCODE_S) {
            mSinaBlogManager.sendToSinaBlog("hali");
            return true;
        }
        else if (keyCode==KeyEvent.KEYCODE_D) {
            mDoubanBlogManager.sendToDoubanGuangbo("test_douban2");
            return true;
        }
        else
            return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (isFinishing()) {
            mStateHolder.cancelTasks();
        }
    }

    protected void popUpBlogBindDialog(int icon,int text)  {
        LayoutInflater factory = LayoutInflater.from(BlogBindActivity.this);
        final View textEntryView = factory.inflate(R.layout.user_blog_account_dialog, null);

        mAlertDlg = new AlertDialog.Builder(BlogBindActivity.this)
        .setIcon(icon)
        .setTitle(text)
        .setView(textEntryView)
        .create();

        mUserName = (EditText)textEntryView.findViewById(R.id.etBlogAccount);
        mPassword = (EditText)textEntryView.findViewById(R.id.etBlogPassword);
        Button btnOk = (Button)textEntryView.findViewById(R.id.btnBlogOk);
        btnOk.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                String account = mUserName.getEditableText().toString();
                String password = mPassword.getEditableText().toString();
                if (account.length() > 0 && password.length() > 0)  {
//                    mStateHolder.startTaskBlogBind(BlogBindActivity.this, account, password);
                    
                    
                }   else {
                    Toast.makeText(BlogBindActivity.this, R.string.error_user_passwd, Toast.LENGTH_LONG).show();
                }
             }
         });
        
        Button btnCancel = (Button)textEntryView.findViewById(R.id.btnBlogCancel);
        btnCancel.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                mAlertDlg.cancel();
             }
         });
        mAlertDlg.show();
    }

    protected void popUpBlogUnbindDialog() {
        AlertDialog dlg = new AlertDialog.Builder(BlogBindActivity.this)
                .setMessage(BlogBindActivity.this.getString(R.string.blog_message_unbind))
                .setPositiveButton(BlogBindActivity.this.getString(R.string.ok),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {

                            }
                        })
                .setNegativeButton(BlogBindActivity.this.getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {

                            }
                        }).create();
        dlg.show();
    }

    private ProgressDialog showProgressDialog() {
        if (mProgressDialog == null) {
            ProgressDialog dialog = new ProgressDialog(this);
            dialog.setMessage(getString(R.string.sign_up_dialog_message));
            dialog.setIndeterminate(true);
            dialog.setCancelable(true);
            mProgressDialog = dialog;
        }
        mProgressDialog.show();
        return mProgressDialog;
    }
}
